#include <iostream>
#include <boost/bind.hpp>
#include "TCPConnection.h"
#include "TCPServer.h"
#include "Config.h"


TCPServer::TCPServer(boost::asio::io_service& ioService, int port)
  : _acceptor(ioService,  boost::asio::ip::tcp::endpoint( boost::asio::ip::tcp::v4(), port))
{
  this->_dbManager.loadDatabase();
}


void TCPServer::startAccept()
{
  TCPConnection::pointer newConnection =  TCPConnection::create(this->_acceptor.io_service());
  this->_acceptor.async_accept(newConnection->socket(),
			       boost::bind(&TCPServer::handleAccept, this, newConnection,
					   boost::asio::placeholders::error));
}

void TCPServer::handleAccept(TCPConnection::pointer newConnection,
			     const boost::system::error_code& error)
{
  if (!error)
    {
      std::cout << "[Server] New client in." << std::endl;
      newConnection->start(this);
      startAccept();
    }
  else
    std::cerr << "[Server] Error on accepting new client: " << error << std::endl;
}
